<?php
/**
 * Main page for accessing resourcepage module. This page is used to view
 * the list of items on a particular resourcepage in three modes:
 * 1. Normal 'view' mode (as for students);
 * 2. 'Edit' mode that shows the list of items with control icons;
 * 3. 'Edit item' mode that shows edit controls for a single item.
 *
 * @copyright &copy; 2006 The Open University
 * @author s.marshall@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package resourcepage
 *//** */
  
require_once("module_resourcepage.php");
$DASHBOARD_COUNTER=7091;
$module=module_resourcepage::$inst;

@include_once(dirname(__FILE__).'/custom_items.php');

$id=optional_param('id',0,PARAM_INT);    // Course Module ID, or
$a=optional_param('a',0,PARAM_INT);     // item ID        
$item=optional_param('item',0,PARAM_ALPHANUM);  // Resourcepage editing item id
$module->obtain_view_info($id,$a,$cm,$course,$resourcepage);

$module->verify_view($cm,$course);

global $CFG;
 
add_to_log($course->id, "resourcepage", "view", "view.php?id=$cm->id", "$resourcepage->id",$cm->id);

$url="create_rss_feed.php?id=".$cm->id;
$pixpath=$CFG->modpixpath.'/'.$module->get_name();
if($resourcepage->publicfeed) {	
    // create a meta tag
    $metatag='<link rel="alternate" type="application/rss+xml" title="RSS" href="'.$url.'"/>';
    $feedicon='&nbsp;<a class="headerfeedicon" href="'.$url.'" title="Atom feed"><img src="'.$pixpath.'/feed.gif" alt=""/></a>';
} else {
    $metatag='';
    $feedicon='';
}

// need to stop editing or updating functions if resourcepage 
// is created to contain a library opml feed

$context=get_context_instance(CONTEXT_MODULE,$cm->id);
if($resourcepage->autocreatetype != ''){
	
 	$editing=false;
	$module->print_header($cm,$course,$resourcepage,'',false, '',
    '',$metatag.'<script type="text/javascript" src="resourcepage.js"></script>',true,'');

		
} else {
	$extraicon=has_capability('moodle/course:manageactivities', $context)
      ? update_course_icon($course->id,true) : '';
    
	$module->print_header($cm,$course,$resourcepage,'',true,$feedicon.$extraicon,
    '',$metatag.'<script type="text/javascript" src="resourcepage.js"></script>',true,'');

	// Main part of page begins
	$editing=isediting($course->id);

} // endif

// Control whether they get to see all the red messages, hidden files etc
$showinfo=$editing || has_capability("moodle/course:viewhiddenactivities",$context);

// Get items (including deleted ones if editing)
if($editing) {
    	$content=$module->get_container_items(
        $resourcepage->containerid,
        $resourcepage->deletedcontainerid);
}
else {    
    $content=$module->get_container_items($resourcepage->containerid);
    $item=false; // Can't be editing single item either thanks
}
  
// Get info about canned text items
$cannedinfo=$module->get_canned_info($resourcepage->id);    
    
// Function for making additem buttons
function print_additem_button($type) {
    $label=get_string('itemtype_'.$type,'resourcepage');
    print '<button onclick="additem(\''.$type.'\')">'.
        $label.'</button>';        
}    
function print_addextension_button($extension,$label) {
    print '<button onclick="addextension(\''.$extension.'\')">'.
        $label.'</button>';        
}    

require_once($CFG->dirroot.'/mod/resourcepage/pagelib.php');
 
// Initialize $PAGE, compute blocks
$PAGE       = page_create_instance($resourcepage->id);
$pageblocks = blocks_setup($PAGE);

// Layout the whole page as three big columns (was, id="layout-table")
print '<div class="mod-rp-view'.($editing ? ' editing' : '').'">';

// The left column ...
// Always have a left column for resource pages
print '<div id="left-column">';
if(($hasleft=blocks_have_content($pageblocks, BLOCK_POS_LEFT)) || $editing) {
    blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT);
}
print '</div>';

// The right column, BEFORE the middle-column.
if (($hasright=blocks_have_content($pageblocks, BLOCK_POS_RIGHT)) || $editing) {
    print '<div id="right-column">';
    blocks_print_group($PAGE, $pageblocks, BLOCK_POS_RIGHT);
    print '</div>';
}

// Start main column
// Always set left column, even if empty for resourecepage
$classes = 'has-left-column';
$classes.=$hasright ? 'has-right-column ' : '';
$classes=trim($classes);
if($classes) {
    print '<div id="middle-column" class="'.$classes.'">';
} else {    
    print '<div id="middle-column">';
}
print skip_main_destination();

// Start resource page overall block
print  '<div class="rp'.($editing ? ' rp_editon' : ' rp_editoff').'">';

// Top canned items (old theme only)
if(preg_match('~^old~',$course->theme) || count($cannedinfo->top)>0) {
    resourcepage_canned::display_position($editing && !$item,$cm->id,$resourcepage->id,$cannedinfo,0);
}

// Main content
$content[0]->display($course,$cm,$editing,$item,false,true,null,null,false,$showinfo);

//references have buttons for export etc - check for any + add
if(!$editing && !$item && $resourcepage->exportrefs==1){
    $hasrefs=resourcepage_view_checkrefin_container($content[0]);
    //create buttons
    if($hasrefs){
        $sesskey=sesskey();
        $but_vals=array();
        $but_vals[0]=get_string('reference_references','resourcepage');
        $but_vals[1]=get_string('reference_selectall','resourcepage');
        $but_vals[2]=get_string('reference_deselectall','resourcepage');
        $but_vals[3]=get_string('reference_exportselected','resourcepage');
        print <<<buts
        <div id='rp_addbuttons'>
		<span>$but_vals[0]:</span>
  		<div id='rp_addbuttons_inner'><form method='post' action='export_references.php'><div>
  		<input class="rp_submit" type="button" name="all" value="$but_vals[1]" title="Select to $but_vals[1] $but_vals[0]" onclick="rp_selRefs(1);return false"/>
    	<input class="rp_submit" type="button" name="none" value="$but_vals[2]" title="Select to $but_vals[2] $but_vals[0]"  onclick="rp_selRefs(0);return false"/>
    	<input class="rp_submit" type="submit" name="export" value="$but_vals[3]" title="Select to $but_vals[3] $but_vals[0]" onclick="rp_exportRefs()"/>
    	<input type="hidden" id="multi_idlist" name="idlist" value ="" /><input type="hidden" name="cmid" value="$cm->id" /><input type="hidden" name="sesskey" value="$sesskey" />&nbsp;</div>
    	</form></div>
		</div>
buts;
    }
}
//checks if any references are in the specified container object (resourcepage_container class)
function resourcepage_view_checkrefin_container($container){
    $numitems=0;
    if($container->get_child_count()){
        $numitems=$container->get_child_count();
    }
    if($numitems>0){
        for($a=0;$a<$numitems;$a++){
            $curitem=$container->get_child($a);
            if(method_exists($curitem,'get_field')){
                if($curitem->get_field('itemtype')=='reference'){
                    return true;
                }
            }else if(method_exists($curitem,'get_child_count')){
                //container... do loop again
                if(resourcepage_view_checkrefin_container($curitem)){
                    return true;
                }
            }
        }
    }
    return false;
}

// test purposes - need to show if only editing
if( ($editing) && (!$item)) {
    
    print '<div id=\'rp_buttons\'>';
    print '<span>Resourcepage : </span>';
    print '<div id=\'rp_buttons_inner\'>';
    print '
    <form method=\'post\' action=\'multiple_resource_copy.php\'><div>
    
    <!--
    Resourcepage(s) to copy/move checked resources to :
    -->';
    
    $sql = 'SELECT
                rp.id, rp.course, rp.name,
                c.shortname
            FROM
                prefix_resourcepage rp,
                prefix_course c
            WHERE
                (rp.autocreatetype <> \'metafeed\' OR rp.autocreatetype IS NULL)
            AND rp.id <> '.$resourcepage->id.'
            AND rp.course = c.id
            AND c.category = ' . $course->category . '
            ORDER BY
                (CASE WHEN c.id = ' . $course->id . ' THEN 0 ELSE 1 END),
                c.shortname,
                rp.name';
    $rs = $module->do_sql($sql);
    
    $sql = 'SELECT
                rpc.id, rpc.title
            FROM
                prefix_resourcepage_containers rpc
            WHERE
                rpc.containertype=\'_section\' AND rpc.title <> \'\' AND rpc.resourcepageid = '.$resourcepage->id;
    $rssections = $module->do_sql($sql);

    $tp = get_string('topofpage','resourcepage');
    $bp = get_string('bottomofpage','resourcepage');

    print '<select name="destination[]">';
    print '<option value="" selected="selected">'.get_string('copymove','resourcepage').'</option>';

    echo '<optgroup label="'.get_string('withinpage','resourcepage').'">';
    echo '<option value="t">'.$tp.'</option>';
    echo '<option value="b">'.$bp.'</option>';

    while(!$rssections->EOF) {
        $title = $rssections->fields['title'];
        echo '<option value="s'.$rssections->fields['id'].'">'.$title.'</option>';
        $rssections->MoveNext();
    }
    echo '</optgroup>';	

    $state = 'start';
    while(!$rs->EOF) {
        $rpcourse = $rs->fields['course'];
        if ($state == 'start' && $rpcourse == $course->id) {
            print '<optgroup label="'.get_string('otherresourcespages','resourcepage').'">';
            $state = 'thiscourse';
        }
        if ($state != 'othercourses' && $rpcourse != $course->id) {
            if ($state == 'thiscourse') {
                print '</optgroup>';
            }
            print '<optgroup label="'.get_string('othercoursespages','resourcepage').'">';
            $state = 'othercourses';
        }
    	$courserpage = $rs->fields['shortname'].' '.$rs->fields['name'];
    	print '<option value="'.$rs->fields['id'].'">'.$courserpage.'</option>';
    	$rs->MoveNext();
    }
    if ($state != 'start') {
        print '</optgroup>';
    }
    print '</select> ';
    
    print '<input type="hidden" id="multi_idlist" name="idlist" value = 
 "" />';
    print '<input type="hidden" name="rpid" value="'.$resourcepage->id.'" />';
    print '<input type="hidden" name="cmid" value="'.$cm->id.'" />';
    print '<input type="hidden" name="courseid" value="'.$course->id.'" />';
    print '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
    print '<input class="rp_submit" type="submit" name="copyto" value="'.get_string('copyto','resourcepage').'"/>';
    print '<input class="rp_submit" type="submit" name="moveto" value="'.get_string('moveto','resourcepage').'"/>';
    print ' &nbsp; <input class="rp_submit" type="submit" name="delete" value="'.get_string('deletemarked','resourcepage').'"/>';
    print '</div></form>';
    print '</div>';
    print '</div>';
}

// Check for array of items to be ordered and/or copied item
    // Check for array of items to be ordered
    if (!empty($_SESSION['orderitems'])) {
        print '<div class="rp_description">';
        print '<form method="post" action="order.php" class="rp_printondemand"><div>'.
              '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
              '<input type="hidden" name="id" value="'.$cm->id.'" />'.
              '<input type="submit" name="vieworder" value="'.get_string('vieworder','resourcepage').'"/>'.
              '</div></form>';
        print '</div>';
    }

    // Check for copied item
    if ($editing && !empty($_SESSION['copieditem'])) {
        print '<div class="rp_cannedbuttons">';
        print '<form method="post" action="pasteitem.php" class="rp_pasteitem"><div>'.
              '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
              '<input type="hidden" name="id" value="'.$cm->id.'" />'.
              '<input type="hidden" name="scrollpos" />'.
              '<input type="submit" name="pasteitem" value="'.get_string('pasteitem','resourcepage').'"/>'.
              '</div></form>';
        print '</div>';
    }

// Bottom canned items
resourcepage_canned::display_position($editing && !$item,$cm->id,$resourcepage->id,$cannedinfo,1);

if($editing) {
    if(!$item) {
        
        // Item type add buttons
?>
<div id="rp_addbuttons">
<span><?php print_string('addnewitem','resourcepage'); ?></span>
<div id='rp_addbuttons_inner'>
<form method="post" action="additem.php" id="rp_addform"><div>
<input type="hidden" name="scrollpos" />
<input type="hidden" name="sesskey" value="<?php p(sesskey()) ?>" />
<input type="hidden" name="id" value="<?php p($cm->id) ?>" />
<input type="hidden" name="itemtype" id="rp_itemtype"/>
<?php   
        print_additem_button('text'); 
        print_additem_button('weblink');
        print_additem_button('file');
        // changed to check for at least one other module now that crosslinks can link to modules
        $othermodules = $module->do_sql("SELECT course FROM prefix_course_modules WHERE course='".$course->id."'");
        if($othermodules->_numOfRows > 1) {
        	print_additem_button('crosslink');
		}
        print_additem_button('section');
        if (function_exists('display_forumlink')) {
            print_additem_button('forumlink');
        }
        print '<br />';

        // Extension add buttons
?>
</div></form>
<form method="post" action="editextension.php" id="rp_addextform"><div>
<input type="hidden" name="scrollpos" />
<input type="hidden" name="sesskey" value="<?php p(sesskey()) ?>" />
<input type="hidden" name="id" value="<?php p($cm->id) ?>" />
<input type="hidden" name="mode" value="add"/>
<input type="hidden" name="extension" id="rp_extension"/>
<?php
        $extensions=$module->get_extensions();
        foreach($extensions as $id => $extension) {
            if(is_a($extension,'resourcepage_extension_pull') && $extension->is_add_allowed($resourcepage,$course)) {
                print_addextension_button($extension->get_name(),$extension->get_display_name());
            }
        }

        // Now list available placeholders (if any...) for placeholder dropdown
        $placeholders=$module->get_available_placeholders();
        if(count($placeholders) > 0) {
?>
</div></form>
<form method="post" action="addplaceholder.php" id="rp_addplaceholderform"><div>
<input type="hidden" name="scrollpos" />
<input type="hidden" name="sesskey" value="<?php p(sesskey()) ?>" />
<input type="hidden" name="id" value="<?php p($cm->id) ?>" />
<select name="placeholder" onchange="if(this.selectedIndex!=0) this.form.submit()">
<option selected="selected"><?php print_string('placeholders','resourcepage'); ?></option>
<?php
            foreach($placeholders as $name=>$object) {
    ?><option value="<?=$name?>"><?=htmlspecialchars($object->get_placeholder_title($name,$course->id))?></option><?php
            }
?>
</select>
<?php
        }
?>
</div></form>

<form method="post" action="displayaddshared.php" id="rp_addsharedform"><div>
<input type="hidden" name="scrollpos" />
<input type="hidden" name="sesskey" value="<?php p(sesskey()) ?>" />
<input type="hidden" name="id" value="<?php p($cm->id) ?>" />
<input type="hidden" name="courseid" value="<?php p($course->id) ?>" />
<button onclick="addshared('resourcepage')">Shared section</button>
</div>
</form>

<form method="post" action="addreferences.php" id="rp_addreferences">
<div><input type="hidden" name="scrollpos" /> <input type="hidden"
	name="sesskey" value="<?php p(sesskey()) ?>" /> <input type="hidden"
	name="id" value="<?php p($cm->id) ?>" /> <input type="hidden"
	name="courseid" value="<?php p($course->id) ?>" />
<button type="submit"><?php print_string('reference_addtitle','resourcepage') ?></button>
</div>
</form>

</div></div>


<?php
    }
    
    // List other pages in initially-hidden <div> for move between pages
?>
<div id="rp_pagemove">
<h3><?php print_string('movetopage','resourcepage');?></h3>
<?php
    $otherpages=$module->get_other_resourcepages($resourcepage->course,$resourcepage->id);
    foreach($otherpages as $id=>$name) {
        ?><div id='otherpage<?=$id?>' onmouseover='selectOtherPage(this)' onmouseout='unselectOtherPage(this)'><?=htmlspecialchars($name)?></div><?php
    }
?>
</div>    
<?php

    // Show deleted section    
    $delcount=$content[1]->get_child_count(); 
    if($delcount>0) {
?>
<h3><?php print_string('deleteditems','resourcepage'); ?> 
(<?php print $delcount; ?>)
<span class='rp_expandcollapse'>
<button id='rp_expand' onclick='toggledel()'><?php print_string('expand','resourcepage');?></button>
<button id='rp_collapse' onclick='toggledel()'><?php print_string('collapse','resourcepage');?></button>
</span>
</h3>
<div id='rp_deleted'>
<?php $content[1]->display($course,$cm,true,$item,false,true,null,null,true,$showinfo); ?>
<div class='rp_deletedfiles'>
    <a href="deletedfiles.php?course=<?php print $course->id ?>"><?php print_string('seedeletedfiles','resourcepage');?></a>
</div>
<?php if(has_capability('moodle/site:doanything', get_context_instance(CONTEXT_SYSTEM, SITEID))) { ?>
<form action="deleteall.php">
    <input type="hidden" name="sesskey" value="<?php p(sesskey()) ?>" />
    <input type="hidden" name="id" value="<?php p($cm->id) ?>" />
    <input type="hidden" name="scrollpos" />
    <input type="submit" value="<?php print_string('deleteall','resourcepage',$delcount); ?>"/>
</form> 
<?php } ?>
</div>
<?php
    } // endif
    
} // endif

//ou-specific begins
if($resourcepage->publicfeed) {	
	$content[0]->display_podcast_console($cm,$resourcepage);
}
//ou-specific ends
?>

</div>
</div>
</div>  
<script type="text/javascript">rp_init();</script>
<?php
 // Main part ends

/// Mark as viewed
    //@completion_set_module_viewed($course,$cm);

    print_footer($course);
    
?>